{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/guanyu/anaconda3/lib/python3.6/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n",
      "  from ._conv import register_converters as _register_converters\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Contains a variant of the densenet model definition.\"\"\"\n",
    "\n",
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import tensorflow as tf\n",
    "\n",
    "slim = tf.contrib.slim\n",
    "\n",
    "\n",
    "def trunc_normal(stddev): return tf.truncated_normal_initializer(stddev=stddev)\n",
    "\n",
    "#current 是传入一个当前层，明显这个函数不是用在最开始的，因为最开始不用dropout\n",
    "def bn_act_conv_drp(current, num_outputs, kernel_size, scope='block'):\n",
    "    current = slim.batch_norm(current, scope=scope + '_bn')\n",
    "    current = tf.nn.relu(current)\n",
    "    current = slim.conv2d(current, num_outputs, kernel_size, scope=scope + '_conv')\n",
    "    current = slim.dropout(current, scope=scope + '_dropout')\n",
    "    return current\n",
    "\n",
    "\n",
    "def block(net, layers, growth, scope='block'):\n",
    "    for idx in range(layers):\n",
    "        bottleneck = bn_act_conv_drp(net, 4 * growth, [1, 1],\n",
    "                                     scope=scope + '_conv1x1' + str(idx))\n",
    "        tmp = bn_act_conv_drp(bottleneck, growth, [3, 3],\n",
    "                              scope=scope + '_conv3x3' + str(idx))\n",
    "        net = tf.concat(axis=3, values=[net, tmp])\n",
    "    return net\n",
    "\n",
    "\n",
    "def densenet(images, num_classes=1001, is_training=False,\n",
    "             dropout_keep_prob=0.8,\n",
    "             scope='densenet'):\n",
    "    \"\"\"Creates a variant of the densenet model.\n",
    "\n",
    "      images: A batch of `Tensors` of size [batch_size, height, width, channels].\n",
    "      num_classes: the number of classes in the dataset.\n",
    "      is_training: specifies whether or not we're currently training the model.\n",
    "        This variable will determine the behaviour of the dropout layer.\n",
    "      dropout_keep_prob: the percentage of activation values that are retained.\n",
    "      prediction_fn: a function to get predictions out of logits.\n",
    "      scope: Optional variable_scope.\n",
    "\n",
    "    Returns:\n",
    "      logits: the pre-softmax activations, a tensor of size\n",
    "        [batch_size, `num_classes`]\n",
    "      end_points: a dictionary from components of the network to the corresponding\n",
    "        activation.\n",
    "    \"\"\"\n",
    "    growth = 24\n",
    "    compression_rate = 0.5\n",
    "\n",
    "    def reduce_dim(input_feature):\n",
    "        return int(int(input_feature.shape[-1]) * compression_rate)\n",
    "\n",
    "    end_points = {}\n",
    "\n",
    "    with tf.variable_scope(scope, 'DenseNet', [images, num_classes]):\n",
    "        with slim.arg_scope(bn_drp_scope(is_training=is_training,\n",
    "                                         keep_prob=dropout_keep_prob)) as ssc:\n",
    "            pass\n",
    "            ###################首层CONVOLUTION########################################\n",
    "            #layers = tf.layers.batch_normalization(images,training=True)\n",
    "            #layers = slim.batch_norm(images, scope='cn1_bn')\n",
    "            #layers = tf.nn.relu(layers)##conv2d包含relu\n",
    "            layers = slim.conv2d(images, 48, [7,7],stride = 2,scope='cn1_conv')\n",
    "            #########################################################################\n",
    "            ###################池化层#################################################\n",
    "            #layers = slim.batch_norm(layers, scope='pool_bn')\n",
    "            #layers = slim.conv2d(layers, 32, [1,1], stride = 2,scope='pool_conv')\n",
    "            #layers = bn_act_conv_drp(layers, growth, [1, 1], scope='transition1_conv2')\n",
    "            layers = slim.max_pool2d(layers, [3, 3], stride=2, scope='pre_pool2')\n",
    "            #########################################################################\n",
    "            end_points['pool']=layers\n",
    "            ###################dense block1##########################################\n",
    "            layers = block(layers,6,growth,scope='dn1')#看论文说，16个channel，是不是说这里的layers就是16呢？\n",
    "            #########################################################################\n",
    "            end_points['dn1']=layers\n",
    "            ###################transaction layers1###################################\n",
    "            layers = bn_act_conv_drp(layers,reduce_dim(layers), [1, 1],scope='tr1_conv')\n",
    "            #layers = reduce_dim(layers)## 其实不太清楚是不是应该这样子降维\n",
    "            layers = slim.avg_pool2d(layers,[2,2],stride = 2,scope='tr1_pool')\n",
    "            #########################################################################\n",
    "            end_points['tr1']=layers\n",
    "            ###################dense block2##########################################\n",
    "            layers = block(layers,12,growth,scope='dn2')\n",
    "            end_points['dn2']=layers\n",
    "            ###################transaction layers2###################################\n",
    "            layers = bn_act_conv_drp(layers,reduce_dim(layers), [1, 1],scope='tr2_conv')\n",
    "            #layers = reduce_dim(layers)\n",
    "            layers = slim.avg_pool2d(layers,[2,2],stride = 2,scope='tr2_pool')\n",
    "            ###################dense block3##########################################\n",
    "            end_points['tr2']=layers\n",
    "            layers = block(layers,24,growth,scope='dn3')\n",
    "            ###################transaction layers3###################################\n",
    "            end_points['dn3']=layers\n",
    "            layers = bn_act_conv_drp(layers,reduce_dim(layers), [1, 1],scope='tr3_conv')\n",
    "            #layers = reduce_dim(layers)\n",
    "            layers = slim.avg_pool2d(layers,[2,2],stride = 2,scope='tr3_pool')\n",
    "            ###################dense block4##########################################\n",
    "            end_points['tr3']=layers\n",
    "            layers = block(layers,16,growth,scope='dn4')\n",
    "            ###################classification layer##################################\n",
    "            end_points['dn4']=layers\n",
    "            #layers = tf.layers.conv.global_avg_pool(layers, name='GlobalAvgPool')\n",
    "            #layers = slim.avg_pool2d(layers, [6, 6], scope='lglobal_pool2') \n",
    "            layers = slim.avg_pool2d(layers, layers.shape[1:3], scope='global_average')\n",
    "            layers = slim.flatten(layers, scope='flatten')\n",
    "            layers = slim.fully_connected(layers, num_classes, activation_fn=None, scope='logits')\n",
    "            logits = layers\n",
    "            end_points['finish'] = tf.nn.softmax(logits, name='Predictions')\n",
    "            #end_points['finish']=layers\n",
    "            \n",
    "            \n",
    "    return logits, end_points\n",
    "\n",
    "\n",
    "def bn_drp_scope(is_training=True, keep_prob=0.8):\n",
    "    keep_prob = keep_prob if is_training else 1\n",
    "    with slim.arg_scope(\n",
    "        [slim.batch_norm],\n",
    "            scale=True, is_training=is_training, updates_collections=None):\n",
    "        with slim.arg_scope(\n",
    "            [slim.dropout],\n",
    "                is_training=is_training, keep_prob=keep_prob) as bsc:\n",
    "            return bsc\n",
    "\n",
    "\n",
    "def densenet_arg_scope(weight_decay=0.004):\n",
    "    \"\"\"Defines the default densenet argument scope.\n",
    "\n",
    "    Args:\n",
    "      weight_decay: The weight decay to use for regularizing the model.\n",
    "\n",
    "    Returns:\n",
    "      An `arg_scope` to use for the inception v3 model.\n",
    "    \"\"\"\n",
    "    with slim.arg_scope(\n",
    "        [slim.conv2d],\n",
    "        weights_initializer=tf.contrib.layers.variance_scaling_initializer(\n",
    "            factor=2.0, mode='FAN_IN', uniform=False),\n",
    "        activation_fn=None, biases_initializer=None, padding='same',\n",
    "            stride=1) as sc:\n",
    "        return sc\n",
    "\n",
    "\n",
    "densenet.default_image_size = 224"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
